package com.wj.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wj.pojo.Menu;
import com.wj.pojo.MenuRole;
import com.wj.pojo.RespBean;
import com.wj.pojo.Role;
import com.wj.service.IMenuRoleService;
import com.wj.service.IMenuService;
import com.wj.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  权限组
 * </p>
 *
 * @author wj
 * @since 1.0.0
 */
@Api(tags = "权限组控制器")
@RestController
@RequestMapping("/system/basic/permission")
public class PermissionGroupController {
    @Resource
    IRoleService roleService;
    @Resource
    IMenuService menuService;
    @Resource
    IMenuRoleService menuRoleService;

    @ApiOperation("获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRole(){
        return roleService.list();
    }

    @ApiOperation("删除角色")
    @DeleteMapping("/")
    public RespBean deleteRoleByIds(Integer[] ids){
        if (roleService.removeByIds(Arrays.asList(ids))){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation("更新角色菜单")
    @Transactional
    @PutMapping("/")
    public RespBean updateRole(Integer rid,Integer[] mids){
        return menuRoleService.updateRoleMenu(rid,mids);
    }

    @ApiOperation("添加角色")
    @PostMapping("/")
    public RespBean addRole(@RequestBody Role role){
        if (!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if (roleService.save(role)){
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    @ApiOperation("获取所有权限的菜单")
    @GetMapping("/menus")
    public List<Menu> getAllPermissionMenu(){
        return menuService.getAllMenu();
    }

    @ApiOperation("根据角色Id查询菜单Id")
    @GetMapping("/menus/{rid}")
    public List<Integer> getPermissionMenuById(@PathVariable Integer rid){
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",rid))
                .stream().map(MenuRole::getMid).collect(Collectors.toList());
    }
}